package com.sunrise.xdoc.view.operator;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.primefaces.context.RequestContext;

import com.sunrise.xdoc.entity.operator.Operator;
import com.sunrise.xdoc.entity.operator.OperatorProfile;
import com.sunrise.xdoc.entity.operator.OperatorRole;
import com.sunrise.xdoc.view.AbstractView;

@ManagedBean
@SessionScoped
public class OperatorRoleView extends AbstractView<OperatorRole> {
	private static final long serialVersionUID = -4553401244651223842L;

	private List<Operator> operators = new ArrayList<>();
	private List<OperatorProfile> profiles = new ArrayList<>();

	@Override
	@PostConstruct
	protected void init() {
		super.init();
		operators = getDaoHelper().getDao(Operator.class).loadAll();
		profiles = getDaoHelper().getDao(OperatorProfile.class).loadAll();
	}

	public void validateStartDate() {
		if (getEditedEntity().getStartDate() != null
				&& getEditedEntity().getStartDate().compareTo(getEditedEntity().getEndDate()) > 0) {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					"Ngày bắt đầu không được sau ngày kết thúc", "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
			FacesContext.getCurrentInstance().validationFailed();
			return;
		}
	}

	@Override
	public void saveOrUpdate() {
		validateStartDate();
		super.saveOrUpdate();
	}

	public Long getSelectedOperatorId() {
		if (getEditedEntity() != null && getEditedEntity().getOperator() != null) {
			return getEditedEntity().getOperator().getId();
		}
		return null;
	}

	public void setSelectedOperatorId(Long selectedOperatorId) {
		for (Operator o : operators) {
			if (selectedOperatorId.equals(o.getId())) {
				getEditedEntity().setOperator(o);
				return;
			}
		}
		getEditedEntity().setOperator(null);
	}

	public Long getSelectedProfileId() {
		if (getEditedEntity() != null && getEditedEntity().getProfile() != null) {
			return getEditedEntity().getProfile().getId();
		}
		return null;
	}

	public void setSelectedProfileId(Long selectedProfileId) {
		for (OperatorProfile p : profiles) {
			if (selectedProfileId.equals(p.getId())) {
				getEditedEntity().setProfile(p);
				return;
			}
		}
		getEditedEntity().setProfile(null);
	}

	public List<Operator> getOperators() {
		return operators;
	}

	public List<OperatorProfile> getProfiles() {
		return profiles;
	}

	@Override
	protected String getDataModelBeanName() {
		return "operatorRoleDataModel";
	}

	@Override
	protected String getDetailPanelViewId() {
		return "operatorRoleDialogId";
	}
}
